#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define UAL_TOP_DIR "/ual"
#define KEY_NAME_HEAD  "key"
#define KEY_ON_VALSTR  "0"
#define KEY_OFF_VALSTR "1"

char *key_name_tail[]  = {"user"};

int key_prev_value[] = {-1};

#define KEY_TOTAL  (sizeof(key_prev_value)/sizeof(key_prev_value[0]))

int scan_key(int keyidx)
{
	FILE *key_value_fphdl;
	char  key_value_fpath[64];
	char  key_value_buf[10];
	int   key_value_int = -1;

	memset(key_value_fpath,0,64);

	sprintf(key_value_fpath,"/%s/%s%s/value", UAL_TOP_DIR, KEY_NAME_HEAD, key_name_tail[keyidx-1]);
	if ((key_value_fphdl = fopen(key_value_fpath, "rb")) == NULL) 
	{
		printf("无法打开文件: %s\n",key_value_fpath);
		exit(1);
	}
	fread(key_value_buf, sizeof(char), sizeof(key_value_buf) - 1, key_value_fphdl);
	fclose(key_value_fphdl);

	key_value_int = atoi(key_value_buf);
	if(key_value_int != key_prev_value[keyidx-1])
	{
        printf("%s%s=%d\n", KEY_NAME_HEAD, key_name_tail[keyidx-1], key_value_int);
        key_prev_value[keyidx-1] = key_value_int;
    }
	return 0;
}

int main(int argc, char **argv)
{
	int keyidx = 0;
    printf("当前按键总数: %d\n", KEY_TOTAL);
    printf("开始读取按键: \n");
    while(1)
    {
		for ( keyidx = 1; keyidx <= KEY_TOTAL; keyidx++ )
		{
	        scan_key(keyidx);
	        usleep(100*1000);
		}
    }
	return 0;
}
